import { useEffect, useCallback } from 'react';
import { message } from 'antd';
import _ from 'lodash';
import type { IOrginDealElementOptions } from './type';

// 判断该用户是否有权限
export const havePermissions = (buttonType: string, buttonPermissions: any) => {
  const hasSave =
    buttonPermissions?.filter((item: any) => item.menuCode === buttonType)?.length > 0;
  if (!hasSave) {
    message.info('请联系管理员获取相关权限');
    return false;
  } else {
    return true;
  }
};

// 处理交易单元数据
export const getDealElementOptions = (data: IOrginDealElementOptions[]) => {
  const _settlemen: Record<string, any> = {};
  let dataObj: Record<string, any> = {};
  // const modalData: any[] = data.map((m: IOrginDealElementOptions) => {

  //   return { ...m, title: m?.label || '', children: _children, key: m?.value || '' };
  // });
  const modalData = data?.map((item: IOrginDealElementOptions) => {
    const children = item?.children?.map((n: any) => ({
      ...n,
      title: n?.stationName,
      key: n?.stationId,
      parentKey: n?.groupId,
      regionId: n?.mraketId || '',
    }));
    dataObj = { ...dataObj, ..._.groupBy(children, 'value') };
    _settlemen[item?.groupId ? item?.groupId : ''] = children;
    return { ...item, key: item?.groupId, title: item?.groupName || '', children };
  });
  return { modalData, value: _.flatten(data?.map((i) => i?.children || [])), dataObj };
};

// 监听浏览器刷新
export const useBeforeunload = () => {
  const onBeforeunload = useCallback((e) => {
    // if (renovate.isRenovate) {
    const confirmationMessage = '当前工作将不被保存，继续执行此操作？';
    (e || window.event).returnValue = confirmationMessage;
    return confirmationMessage;
    // }
  }, []);
  useEffect(() => {
    window.addEventListener('beforeunload', onBeforeunload);
    return () => {
      window.removeEventListener('beforeunload', onBeforeunload);
    };
  }, []);
  return;
};
